package ru.arriah.servicedesk.web.dispatcher.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.mail.MailSender;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.DepartmentBean;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.MailTemplateBean;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.ejb.UtilityManagerLocalHome;
import ru.arriah.servicedesk.ejb.UtilityManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class AddRequestAction extends DumbAction {
   protected RequestFormErrorBean requestFormErrorBean;
   
   protected OrganizationManagerLocalHome organizationManagerHome;
   protected RequestManagerLocalHome requestManagerHome;
   protected ClientManagerLocalHome clientManagerHome;
   protected GroupManagerLocalHome groupManagerHome;
   protected EmployeeManagerLocalHome employeeManagerHome;
   protected UtilityManagerLocalHome utilityManagerHome;
   
   
   public AddRequestAction() throws NamingException {
      super();

      requestManagerHome = Utils.getRequestManagerHomeInterface();      
      organizationManagerHome = Utils.getOrganizationManagerHomeInterface();      
      clientManagerHome = Utils.getClientManagerHomeInterface();      
      groupManagerHome = Utils.getGroupManagerHomeInterface();      
      employeeManagerHome = Utils.getEmployeeManagerHomeInterface();      
      utilityManagerHome = Utils.getUtilityManagerHomeInterface();      
   }
   
   /**
    * send mail to lead executor
    * @param requestBean
    */
   private void sendMail(RequestBean requestBean) {
      try {
        EmployeeManagerLocalObject employeeManager = 
          employeeManagerHome.create();
        UtilityManagerLocalObject utilityManager = 
          utilityManagerHome.create();
        
        MailSender mailSender = new MailSender();
                   
        mailSender.setSmtpPort(config.getProperty("SMTP_PORT"));
        mailSender.setHostName(config.getProperty("SMTP_HOST_NAME"));
        mailSender.setFrom(config.getProperty("FROM"));
        mailSender.setCharset("UTF-8");
        
        mailSender.setAuthentication(
          config.getProperty("LOGIN"), 
          config.getProperty("PASSWORD")
        );
        
        MailTemplateBean mailTemplate = 
          utilityManager.selectMailTemplateByKey("NEW_REQUEST_TO_LEAD");
        
        EmployeeBean leadExecutor = 
          employeeManager.selectEmployee(requestBean.getLeadExecutorId());
        
        mailSender.setSubject(mailTemplate.getSubject());              
        
        mailSender.setContent(
          String.format(            
            mailTemplate.getBody(),
            leadExecutor.getFirstName(),
            leadExecutor.getLastName(),
            new Date(),
            requestBean.getId(),
            config.getProperty("HOST")
          )
        );       
                       
        mailSender.addRecipient(leadExecutor.getEmail());         
        
        mailSender.send();
        
        utilityManager.remove();
        employeeManager.remove();
      } catch (Exception e) {
        handleException(e, "sendMail");       
      }
    }
   
   
   
   /**
    * Validate request
    * @param requestBean
    * @return
    */
   private boolean isValid(RequestBean requestBean) {
     requestFormErrorBean = new RequestFormErrorBean();
     boolean result = true;
     
     if(requestBean.getOrganizationId() == 0) {
       requestFormErrorBean.setOrganization(
         config.getProperty("ERROR.REQUESTFORM.ORGANIZATION")
       );
       result = false;
     }
     
     if(requestBean.getDepartmentId() == 0) {
       requestFormErrorBean.setDepartment(
         config.getProperty("ERROR.REQUESTFORM.DEPARTMENT")
       );
       result = false;
     }
     
     if(requestBean.getClientId() == 0) {
       requestFormErrorBean.setClient(
         config.getProperty("ERROR.REQUESTFORM.CLIENT")
       );
       result = false;
     }
     
     if (requestBean.getDispatcherText() == null || requestBean.getDispatcherText().equals("")) {
       requestFormErrorBean.setDispatcherText(
         config.getProperty("ERROR.REQUESTFORM.DISPATCHERTEXT")
       );
       result = false;
     }
     
     if(requestBean.getGroupId() == 0) {
       requestFormErrorBean.setGroup(
         config.getProperty("ERROR.REQUESTFORM.GROUP")
       );
       result = false;
     }
     
     if(requestBean.getRequestTypeId() == 0) {
       requestFormErrorBean.setRequestType(
         config.getProperty("ERROR.REQUESTFORM.REQUESTTYPE")
       );
       result = false;
     }          
     
     return result;
   }

   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {
       
       RequestManagerLocalObject requestManager = 
         requestManagerHome.create();
       EmployeeManagerLocalObject employeeManager = 
         employeeManagerHome.create();
       
       RequestBean requestBean = new RequestBean();
       int userId = (Integer)request.getSession().getAttribute("userId");       
       
       requestBean.setRegNumber(request.getParameter("regNumber"));
       
       requestBean.setOrganizationId(
         idVal(request.getParameter("organization_id"))
       );
       
       requestBean.setDepartmentId(
         idVal(request.getParameter("department_id"))
       ); 
       
       requestBean.setClientId(
         idVal(request.getParameter("client_id"))
       );
       
       requestBean.setRoom(request.getParameter("room"));
       
       requestBean.setDispatcherText(
         request.getParameter("dispatcherText")
       );
       
       requestBean.setGroupId(
         idVal(request.getParameter("group_id"))
       );
       
       requestBean.setRequestTypeId(
        idVal(request.getParameter("requesttype_id"))
       );
       
       requestBean.setComment(
         request.getParameter("comment")
       );
       
       requestBean.setRegistrationDate(new Date());
       requestBean.setStatusId(3);
       requestBean.setPriority(3);
       requestBean.setRegistratorId(userId);
       
       int leadExecutorId = 
         employeeManager.selectLeadExecutorId(
           requestBean.getGroupId()
         );       
       requestBean.setLeadExecutorId(leadExecutorId); 
              
       
       //if request not valid
       if(!this.isValid(requestBean)) {     
         OrganizationManagerLocalObject organizationManager = 
           organizationManagerHome.create();         
         ClientManagerLocalObject clientManager = 
           clientManagerHome.create();         
         GroupManagerLocalObject groupManager = 
           groupManagerHome.create();
         
         //TODO replace static id to real id
         Collection<DepartmentBean> departmentsList =
           organizationManager.selectDepartments(1);
         
         Collection<OrganizationBean> organizationsList = 
           organizationManager.selectOrganizations();
         
         Collection<ClientBean> clientsList = 
           clientManager.selectClients();
         
         Collection<RequestTypeBean> requestTypesList = 
           requestManager.selectRequestTypes();
         
         Collection<GroupBean> groupsList = 
           groupManager.selectGroups();
                   
         organizationManager.remove();
         clientManager.remove();
         requestManager.remove();
         groupManager.remove();
         employeeManager.remove();
                           
         request.setAttribute("groupsList", groupsList);
         request.setAttribute("requestTypesList", requestTypesList);
         request.setAttribute("organizationsList", organizationsList);
         request.setAttribute("clientsList", clientsList);
         request.setAttribute("departmentsList", departmentsList);
         request.setAttribute("requestBean", requestBean);         
         request.setAttribute("error", requestFormErrorBean);
         addErrorMessage(request, config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID"));
                 
         return actionMapping.getFailureTarget();
       }       
       
       /* Try to add request*/
       
       if (requestManager.addRequest(requestBean, userId)) {
         sendMail(requestBean); 
         addInfMessage(
            request, 
            String.format(config.getProperty("INF.REQUEST_ADDED"), requestBean.getId())
         );         
       } else
          addErrorMessage(
             request, 
             config.getProperty("ERROR.REQUEST_NOT_ADDED")
          );
                             
       requestManager.remove();
       employeeManager.remove();                   
       
       return actionMapping.getSuccessTarget();
    } catch (Exception e) {
       handleException(e, "execute");
       throw new InternalException("ErrorMessage.internal");
    }
   }
}